<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\model;


use Illuminate\Queue\Queue;
use think\Db;

/**
 * Game模型
 */
class BetsLogSubscribe extends ModelBase
{

    protected $insert = ['create_time','trade_no'];

    /**
     * AI流水号自动完成
     */
    public function setTradeNoAttr()
    {

        return 'BT'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(1000,9999);
    }

    /**
     * 连用户表
     */
    public function user(){
        return $this->belongsTo('Member','user_id','id');
    }

    /**
     * 连彩种表
     */
    public function lottery(){
        return $this->belongsTo('Lottery','lottery_id','id');
    }

    /**
     * 连玩法表
     */
    public function play(){
        return $this->belongsTo('LotteryPlay','play_id','id');
    }


    /**
     * 获取状态信息内容
     */
    public function getStateHtmlAttr(){

        switch ($this->state){
            case 1:
                $html='<span class="el-tag el-tag--mini">未开奖</span>';
                break;
            case 2:
                $html='<span class="el-tag el-tag--success">中奖</span>';
                break;
            case 3:
                $html='<span class="el-tag el-tag--danger">未中奖</span>';
                break;

            case 4:
                $html='<span class="el-tag el-tag--danger">已撤单</span>';
                break;

        }
        return $html;
    }
    /**
     * 开奖号码
     */
    public function getRewardNumberAttr()
    {

        $info=LotteryResult::get(['lottery_id'=>$this->lottery_id,'round'=>$this->round]);
        if($info){
           return $info['number'];
        }
        return '';
    }
    /**
     * 时间自动完成
     */
    public function setCreateTimeAttr()
    {

        return TIME_NOW;
    }

    /**
     * 时间自动完成
     */
    public function getCreateTimeAttr($value)
    {

        return date('Y-m-d H:i:s',$value);
    }




    /**
     * 开奖结算
     */
    public function  new_settlement($res){
        $hit_number = $res['number'];
        $play=$this->play;
        $lottery=$this->lottery;
        $cate_symbol=$lottery->cate->symbol;
        if($this->is_old==1){
            include_once(ROOT_PATH.'extend/kaijiang/oldplay.php');
            $_zhushuyzclass = "Lib\\kaijiang\\oldplay";
            $_obj = new $_zhushuyzclass();
            $_fun=$play['symbol'];
            $arr=[
                'func'=>$_fun,
                'opencode'=>$hit_number,
                'tzcode'=>$this->number,
                'class2'=>$play->data['name']
            ];
            $iszjokcount=$_obj->check($arr);

        }else{
            include_once(ROOT_PATH.'extend/kaijiang/'.$cate_symbol.'.php');
            $_zhushuyzclass = "Lib\\kaijiang\\{$cate_symbol}";
            $_fun=$play['symbol'];
            $arr=[
                'playid'=>$_fun,
                'opencode'=>$hit_number,
                'tzcode'=>$this->number,
            ];
            $arrs[]=$arr;
            $_obj = new $_zhushuyzclass($arrs);
            $res=$_obj->check();

            $iszjokcount=$res[0]['zjcount'];
        }



       if($iszjokcount=='x5'){
           $reward_count=0;
       }else{
           $reward_count=$iszjokcount['zjcount'];
       }

        $zjcount=0;
        if($reward_count>0){
            //中奖奖金
            if(strstr($this->odds,'|')){
                for($i=0;$i<count($iszjokcount['zjcount']);$i++){
                    if($reward_count[$i]>0){
                        $zjcount = $reward_count[$i];
                        break;
                    }
                }
            }else{
                $zjcount=$iszjokcount['zjcount'];
            }
            $reward_money=self::$cate_symbol([
                'mode'=>$this->odds,
                'iszjcount'=>$reward_count,
                'beishu'=>$this->mult,
                'iszjokcount'=>$iszjokcount,
                'amount'=>$this->money,
                'itemcount'=>$this->injection_number,
                'zjcount'=>$zjcount,
                'yjf'=>$this->univalent
            ]);

            $reward_money_total=$reward_money;
            $this->reward_money=$reward_money_total;

            if($reward_money_total<$this->money){
                $this->is_winner=2;
            }else{
                if($this->programme_id>0){
                    $programme=PlanUserProgramme::get($this->programme_id);
                    $plan_programme=$programme->programme;
                    //当前盈利
                    $programme->current_win_money+=($reward_money_total-$this->money);
                    //当前亏损
                    $programme->current_lose_money-=($reward_money_total-$this->money);
                    $plan_programme->win_count+=1;
                }

                //赢回馈
                $point=getConfig('yuce_winner_point');
                if($point>0 && $this->user->is_king>0 && $this->user->level_id>=2){
                    $user_account=UserAccount::check(['user_id'=>$this->user_id,'wallet_id'=>1],false);

                    $user_account->balance+=getConfig('yuce_winner_point');
                    $user_account->save();

                    //写入流水
                    UserAccountLog::create([
                        'user_id'=>$this->user_id,
                        'wallet_id'=>1,
                        'lottery_id'=>$this->lottery_id,
                        'before_blance'=>$user_account->balance-$point,
                        'after_blance'=>$user_account->balance,
                        'remark'=>'用户预约下注'.$this->round.'期赢返点'.$point,
                        'number'=>$point,
                        'type'=>32,
                        'is_add'=>1,
                    ]);
                }


            }


            $this->state=2;
            $this->reward_arr=implode(',',$iszjokcount['reward_arr']);


        }else{

            //未中奖
            $this->state=3;
            $this->is_winner=2;

            if($this->programme_id>0){
                $programme=PlanUserProgramme::get($this->programme_id);
                $plan_programme=$programme->programme;
                //当前盈利
                $programme->current_win_money-=$this->money;
                //当前亏损
                $programme->current_lose_money+=$this->money;

            }


        }

        $member=Member::get($this->user_id);
        if($this->is_winner==1){
            //赢次数
            $member->forecast_win_count+=1;
        }else{
            //输次数
            $member->forecast_lose_count+=1;
        }
        //完成周期
        $order=self::where(['user_id'=>$this->user_id,'state'=>['gt',1]])->order('id desc')->find();

        if($order){
            if($order['is_winner']!=$this->is_winner){
                $member->forecast_success_cycle+=1;
            }
        }
        if($this->programme_id>0) {
            $plan_programme->win_rate = format_money($plan_programme->win_count / $plan_programme->bets_count * 100, 2);
            $plan_programme->save();
            if ($programme->is_stop_win == 1) {
                if ($programme->current_win_money >= $programme->stop_win_money) {
                    $programme->state = 4;
                    $programme->has_end_time = TIME_NOW;
                }
            }
            if ($programme->is_stop_lose == 1) {
                if ($programme->current_lose_money >= $programme->stop_lose_money) {
                    $programme->state = 4;
                    $programme->has_end_time = TIME_NOW;
                }
            }
            if ($programme['current_round'] == $programme['round']) {
                $programme->state = 4;
                $programme->has_end_time = TIME_NOW;
            }

            $programme->save();
        }

        //正确率
        $error_rate=format_money($member->forecast_win_count/($member->forecast_win_count+$member->forecast_lose_count)*100,2);
        $member->forecast_accuracy_rate=$error_rate;

        //当前连中
        if($order){

            if($this->is_winner==1){
                //这把赢
                if($order['is_winner']==2){
                    //上把输
                    $member->forecast_continuous_error=0;
                    $member->forecast_current_win=1;
                }else{
                    //上把赢
                    $member->forecast_current_win+=1;
                    if( $member->forecast_current_win>$member->forecast_max_win){
                        //最大连赢
                        $member->forecast_max_win=$member->forecast_current_win;
                    }
                }
            }else{
                //这把输
                $member->forecast_current_win=0;
                if($order['is_winner']==1){
                    //上把赢
                    $member->forecast_current_win=0;
                    $member->forecast_continuous_error=1;

                }else{
                    //上把输
                    $member->forecast_continuous_error+=1;
                    if( $member->forecast_continuous_error>$member->forecast_max_continuous_error){
                        //最大连输
                        $member->forecast_max_continuous_error=$member->forecast_continuous_error;
                    }
                }


            }
        }else{
            if($this->is_winner==1){
                if( $member->forecast_current_win>0){
                    $member->forecast_current_win+=1;
                    if( $member->forecast_current_win>$member->forecast_max_win){
                        //最大连赢
                        $member->forecast_max_win=$member->forecast_current_win;
                    }

                }else{
                    $member->forecast_current_win=1;
                }
                $member->forecast_continuous_error=0;
            }else{
                if( $member->forecast_continuous_error>0){
                    //当前连输
                    $member->forecast_continuous_error+=1;
                    if( $member->forecast_continuous_error>$member->forecast_max_continuous_error){
                        //最大连输
                        $member->forecast_max_continuous_error=$member->forecast_continuous_error;
                    }

                }else{
                    $member->forecast_continuous_error=1;
                }
                $member->forecast_current_win=0;
            }

        }

        $member->save();

        //第三方挂机
        if($this->is_plan==1){
            $plan=ThirdPlan::get($this->plan_id);
            if($this->is_winner==1){
                //赢次数
                $plan->forecast_win_count+=1;
            }else{
                //输次数
                $plan->forecast_lose_count+=1;
            }
            //完成周期
            $order=self::where(['user_id'=>$this->user_id,'state'=>['gt',1]])->order('id desc')->find();

            if($order){
                if($order['is_winner']!=$this->is_winner){
                    $plan->forecast_success_cycle+=1;
                }
            }
            //正确率
            $error_rate=format_money($plan->forecast_win_count/($plan->forecast_win_count+$plan->forecast_lose_count)*100,2);
            $plan->forecast_accuracy_rate=$error_rate;

            //当前连中
            if($order){

                if($this->is_winner==1){
                    //这把赢
                    if($order['is_winner']==2){
                        //上把输
                        $plan->forecast_continuous_error=0;
                        $plan->forecast_current_win=1;
                    }else{
                        //上把赢
                        $plan->forecast_current_win+=1;
                        if( $plan->forecast_current_win>$plan->forecast_max_win){
                            //最大连赢
                            $plan->forecast_max_win=$plan->forecast_current_win;
                        }
                    }
                }else{
                    //这把输
                    $plan->forecast_current_win=0;
                    if($order['is_winner']==1){
                        //上把赢
                        $plan->forecast_current_win=0;
                        $plan->forecast_continuous_error=1;

                    }else{
                        //上把输
                        $plan->forecast_continuous_error+=1;
                        if( $plan->forecast_continuous_error>$plan->forecast_max_continuous_error){
                            //最大连输
                            $plan->forecast_max_continuous_error=$plan->forecast_continuous_error;
                        }
                    }


                }
            }else{
                if($this->is_winner==1){
                    if( $plan->forecast_current_win>0){
                        $plan->forecast_current_win+=1;
                        if( $plan->forecast_current_win>$plan->forecast_max_win){
                            //最大连赢
                            $plan->forecast_max_win=$plan->forecast_current_win;
                        }

                    }else{
                        $plan->forecast_current_win=1;
                    }
                    $plan->forecast_continuous_error=0;
                }else{
                    if( $plan->forecast_continuous_error>0){
                        //当前连输
                        $plan->forecast_continuous_error+=1;
                        if( $plan->forecast_continuous_error>$plan->forecast_max_continuous_error){
                            //最大连输
                            $plan->forecast_max_continuous_error=$plan->forecast_continuous_error;
                        }

                    }else{
                        $plan->forecast_continuous_error=1;
                    }
                    $plan->forecast_current_win=0;
                }

            }

            $plan->save();

            $roud=substr($this->round,-3)+0;
            if($reward_count>0){
                $roud=substr($this->round,-3)+0;
                PlanNumber::where(['id'=>$this->plan_number_id])->update(['state'=>2,'reward_number'=>$roud,'reward_round'=>$this->round]);

            }else{
                $number_info=PlanNumber::get($this->plan_number_id);

                if($number_info['end_number']==$roud){
                    $number_info->state=3;
                    $number_info->save();
                }else{
                    $number_info->end_round+=1;
                    $number_info->save();
                }


            }
        }

        $this->save();

    }


    public function subscribe_add_lottery($data){




            //同步下注
            $jobHandlerClassName  = 'app\api\job\Consumer';

            // 2.当前任务归属的队列名称，如果为新队列，会自动创建
            $jobQueueName  	  = "ConsumerJobQueue";


            //当前期数同步下注
            $arr = array(
                'user_id'=>$data['user_id'],
                'lottery_id'=>$data['lottery_id'],
                'play_id'=>$this->play_id,
                'round'=>$data['round'],
                'number'=>$data['number'],
                'injection_number'=>$data['injection_number'],
                'user_investment_id'=>0,
                'mult'=>$data['mult'],
                'univalent'=>$data['univalent'],
                'entrust_count'=>0,
                'state'=>1,//1待开奖  2中奖 3:未中
                'money'=>$data['money'],   //本金
                'create_time'=>TIME_NOW,
                'odds'=>$data['odds'],
                'point_odds'=>$data['point_odds'],
                'return_point_money'=>$data['return_point_money'],
                'is_old'=>$this->is_old,
                'trade_no'=>'BT'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(1000,9999),

            );
            $game=[
                'user_id'=>$data['user_id'],
                'king_id'=>0,
                'user_investment_id'=>0,
                'investment_id'=>0,
                'type'=>4,
                'entrust_count'=>0,
                'state'=>3,
                'order_no'=>$arr['trade_no'],
                'number'=>$data['money'],
                'create_time'=>TIME_NOW,
                'users'=>''

            ];
        Db::name('bets_log')->insert($arr);
        Db::name('games_log')->insert($game);



        //等级升级
        $member=Member::get($data['user_id']);

        if($member['is_banker']==1) {

            Queue::push($jobHandlerClassName, $arr['trade_no'], $jobQueueName);

        }
        return ['status'=>0,'msg'=>'下注成功'];



    }





    protected function lhc($res){

        $okamount = 0;
        if(strstr($res["mode"],'|')){
            $mode = explode('|',$res["mode"]);
            for($i=0;$i<count($mode);$i++){
                if($res["iszjcount"][$i]>0){
                    $okamount +=($res['amount']/$res['itemcount'])*$mode[$i]*$res['beishu']*$res['iszjokcount'][$i];
                }
            }
        }else{
            $okamount = ($res['amount']/$res['itemcount'])*$res['mode']*$res['beishu']*$res['iszjokcount'];
        }

        return $okamount;
    }

    protected function ssc($res){
        $okamount =$res['mode']*$res['zjcount']*$res['beishu']*$res['yjf'];
        return $okamount;
    }
    protected function k3($res){
        $okamount = ($res['amount']/$res['itemcount'])*$res['mode']*$res['zjcount'];
        return $okamount;
    }
    protected function x5($res){
        $okamount = 0;
        if(strstr($res["mode"],'|')){
            $amount = explode('|',$res["mode"]);
            for($i=0;$i<count($amount);$i++){
                if($res['iszjokcount'][$i]!=0){
                    $okamount = $amount[$i]*$res['iszjokcount'][$i]*$res['beishu']*$res['yjf'];
                }
            }
        }else{

            $okamount =$res['mode']*$res['zjcount']*$res['beishu']*$res['yjf'];
        }
        return $okamount;
    }
    protected function kl10f($res){
        $okamount = 0;
        $rules = M('wanfa')->where(['typeid'=>$res['typeid'],'playid'=>$res['playid']])->find();
        if($rules){
            $defaultfandian = 0.13;
            $userinfo = [];
            $userinfo = M('member')->where(['id'=>$res['uid']])->find();
            $fandian = $userinfo['fandian'];
            if($rules['rate']>0){
                $amount = $res['mode']  *$res['yjf']*$res['beishu'];
                $okamount = $amount*$res['zjcount'];
            }else{
                $amount = (($rules['maxjj']/2) - ($defaultfandian-($fandian/100-$res['repoint']/100)) * $rules['totalzs'])*$res['yjf']*$res['beishu'];
                $okamount = $amount*$res['zjcount'];
            }
        }else{

        }
        return $okamount;
    }
    protected function pk10($res){
        $okamount =$res['mode']*$res['zjcount']*$res['beishu']*$res['yjf'];
        return $okamount;
    }
    protected function dpc($res){

        $okamount =$res['mode']*$res['zjcount']*$res['beishu']*$res['yjf'];
        return $okamount;
    }
    protected function keno($res){
        $okamount = 0;
        if(strstr($res["mode"],'|')){
            $amount = explode('|',$res["mode"]);
            for($i=0;$i<count($amount);$i++){
                if($res["iszjcount"][$i]>0){
                    $okamount = $okamount+($amount[$i]*$res["iszjcount"][$i])*$res['beishu']*$res['yjf'] ;
                    break;
                }
            }
        }else{
            $okamount =$res['mode']*$res['zjcount']*$res['beishu']*$res['yjf'];
        }
        return $okamount;

    }
}
